package com.hmdp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.hmdp.dto.Result;
import com.hmdp.dto.UserDTO;
import com.hmdp.entity.Follow;
import com.hmdp.entity.User;
import com.hmdp.mapper.FollowMapper;
import com.hmdp.service.IFollowService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.service.IUserService;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.UserHolder;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Set;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class FollowServiceImpl extends ServiceImpl<FollowMapper, Follow> implements IFollowService {

    @Resource(name = "stringRedisTemplate")
    private StringRedisTemplate redisTemplate;
    @Resource
    private IUserService userService;

    /**
     * 关注/取关用户
     * @param followUserId 要关注的用户id
     * @param isFollow true 关注 false 取关
     * @return
     */
    @Override
    public Result follow(Long followUserId, Boolean isFollow) {
        //判断关注还是取关
        if (isFollow == null) {
            return Result.fail("参数不能未空值！");
        }
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        String key = RedisConstants.FOLLOW_USER_KEY + userId;
        if (isFollow) {
            //关注，新增数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            follow.setCreateTime(LocalDateTime.now());
            boolean saveSuccess = save(follow);
            if (!saveSuccess) {
                return Result.fail("关注失败。");
            }
            //将关注的用户id添加到redis中当前用户id对应的set中
            redisTemplate.opsForSet().add(key, followUserId.toString());
        } else {
            //取关，删除数据
            Follow follow = new Follow();
            follow.setUserId(userId);
            follow.setFollowUserId(followUserId);
            QueryWrapper<Follow> wrapper = new QueryWrapper<>();
            wrapper.eq("user_id", userId).eq("follow_user_id", followUserId);
            boolean removeSuccess = remove(wrapper);
            if (!removeSuccess) {
                return Result.fail("取关失败。");
            }
            //将关注的用户id从redis中当前用户id对应的set中移除
            redisTemplate.opsForSet().remove(key, followUserId.toString());
        }
        return Result.ok();
    }

    /**
     * 查询是否关注了followUserId
     * @param followUserId 要查询关注状态的用户id
     * @return
     */
    @Override
    public Result queryFollowStatus(Long followUserId) {
        //查询tb_follow中对应记录是否存在，不存在则未关注，存在则关注
        //获取当前用户id
        Long userId = UserHolder.getUser().getId();
        Integer followCnt = query().eq("user_id", userId).eq("follow_user_id", followUserId).count();
        if (followCnt > 0) {
            return Result.ok(true);
        } else {
            return Result.ok(false);
        }
    }

    /**
     * 查询当前用户和targetUserId (目标用户) 共同关注的人
     * @param targetUserId 目标用户
     * @return
     */
    @Override
    public Result queryCommonFollows(Long targetUserId) {
        //当前用户id
        Long userId = UserHolder.getUser().getId();
        //当前用户key
        String key1 = RedisConstants.FOLLOW_USER_KEY + userId;
        //目标用户key
        String key2 = RedisConstants.FOLLOW_USER_KEY + targetUserId;
        //查询当前用户和targetUserId (目标用户) 共同关注的人 (求redis中set的交集)
        Set<String> commonFollowIds = redisTemplate.opsForSet().intersect(key1, key2);
        ArrayList<UserDTO> userDTOS = new ArrayList<>();
        //无共同关注
        if (commonFollowIds == null || commonFollowIds.isEmpty()) {
            return Result.ok(userDTOS);
        }
        //解析用户id，查询用户，封装集合
        for (String followIdStr : commonFollowIds) {
            Long followId = Long.parseLong(followIdStr);
            User user = userService.getById(followId);
            UserDTO userDTO = new UserDTO();
            BeanUtils.copyProperties(user, userDTO);
            userDTOS.add(userDTO);
        }
        return Result.ok(userDTOS);
    }
}
